package com.taotao.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UploadImgController {

	@ResponseBody
	@RequestMapping("/img/upload")
	public void uploadFile(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		/*
		 * String fileName = "C:\\Users\\guonl\\Desktop\\image06.jpeg"; File
		 * file = new File(fileName); // 判断文件是否存在如果不存在就返回默认图标 // if
		 * (!(file.exists() && file.canRead())) { // file = new
		 * File(request.getSession().getServletContext().getRealPath("/") +
		 * "resource/icons/auth/root.png"); // } FileInputStream inputStream =
		 * new FileInputStream(file); byte[] data = new byte[(int)
		 * file.length()]; int length = inputStream.read(data);
		 * inputStream.close(); // response.setContentType("image/png");
		 * response.setContentType("image/jpeg"); OutputStream stream =
		 * response.getOutputStream(); stream.write(data); stream.flush();
		 * stream.close();
		 */

		// String url="http://192.168.2.200/123.jpeg";
		String url = "http://192.168.2.200/789.jpeg";
		byte[] l_byte = null;
		try {
			l_byte = image2BytesFromURL(url);
			// l_byte = image2BytesFromURL(l_filename);

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		/*
		 * BASE64Encoder encode = new BASE64Encoder(); String base64 =
		 * encode.encode(l_byte); System.out.println(base64);
		 */
		response.setContentType("image/jpeg");
		response.getOutputStream().write(l_byte);

	}

	private byte[] image2BytesFromURL(String address) throws Exception {

		URL url = new URL(address);
		InputStream is = url.openStream();
		ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
		/*byte[] bytes = new byte[is.available()];
		// 将文件内容写入字节数组，提供测试的case
		System.out.println(bytes.length);
		is.read(bytes);*/
		byte[] temp = new byte[1024];
		int size = 0;
		while ((size = is.read(temp)) != -1) {
			out.write(temp, 0, size);
		}
		is.close();
		byte[] bytes = out.toByteArray();
		return bytes;
	}

	public byte[] getContent2(String filePath) throws IOException {

		FileInputStream in = new FileInputStream(filePath);
		ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
		System.out.println("bytes available:" + in.available());
		
		byte[] temp = new byte[1024];
		int size = 0;
		while ((size = in.read(temp)) != -1) {
			out.write(temp, 0, size);
		}
		in.close();
		byte[] bytes = out.toByteArray();
		System.out.println("bytes size got is:" + bytes.length);

		return bytes;
	}

}
